import streamlit as st
from globals import FAVICON, APP_NAME, PRODUCTS_PAGE_NAME, PRODUCTS_KEY_BASE
from database.queries.user_orm import SynOrmUserQueries
from database.queries.product_orm import SynOrmProductQueries
from widgets.menu import menu_with_redirect
from widgets.default_products import default_products_form


st.set_page_config(
    page_title=f"{APP_NAME} • {PRODUCTS_PAGE_NAME}", 
    page_icon=FAVICON, 
    initial_sidebar_state="collapsed",
)
# Sidebar menu. Redirect if not authenticated
menu_with_redirect()

default_products_form()

if "username" in st.session_state:
    user = SynOrmUserQueries.get_user_by_username(st.session_state["username"])
    
    with st.form(
        key=f"{PRODUCTS_KEY_BASE}_product_add_form", 
        clear_on_submit=True
    ):
        st.subheader("Добавить продукт")
        
        name = st.text_input(
            label="Название продукта (должно быть уникально и не пустое)",
            key=f"{PRODUCTS_KEY_BASE}_product_name",
        )
        proteins_100g = st.number_input(
            label="Белки на 100 гр",
            min_value=0.0,
            step=0.1,
            key=f"{PRODUCTS_KEY_BASE}_product_proteins_100g",
        )
        fats_100g = st.number_input(
            label="Жиры на 100 гр",
            min_value=0.0,
            step=0.1,
            key=f"{PRODUCTS_KEY_BASE}_product_fats_100g",
        )
        carbs_100g = st.number_input(
            label="Углеводы на 100 гр",
            min_value=0.0,
            step=0.1,
            key=f"{PRODUCTS_KEY_BASE}_product_carbs_100g",
        )
        price_100g = st.number_input(
            label="Цена за 100 гр",
            min_value=0.0,
            step=0.1,
            key=f"{PRODUCTS_KEY_BASE}_product_price_100g",
        )
        ready_to_eat = st.checkbox(
            label="Готово к употреблению?",
            key=f"{PRODUCTS_KEY_BASE}_product_ready_to_eat",
        )
        max_per_day = st.number_input(
            label="Максимум за день (гр)",
            min_value=20.0,
            value=10000.0,
            step=10.0,
            key=f"{PRODUCTS_KEY_BASE}_product_max_per_day",
        )
        description = st.text_area(
            label="Описание продукта",
            key=f"{PRODUCTS_KEY_BASE}_product_description",
        )
        if st.form_submit_button(
            label="Добавить",
            type="primary",
        ):
            product_dict = {
                "name": name,
                "username": user.username,
                "proteins_100g": proteins_100g,
                "fats_100g": fats_100g,
                "carbs_100g": carbs_100g,
                "price_100g": price_100g,
                "ready_to_eat": ready_to_eat,
                "max_per_day": max_per_day,
                "description": description,
            }
            if product_dict["name"] is None or product_dict["name"] == "":
                st.error("Имя не должно быть пустым", icon="🚫")
            elif product_dict["name"] in [p.name for p in user.products]:
                st.error("Продукт с таким именем уже существует", icon="🚫")
            else:
                SynOrmProductQueries.insert_product(**product_dict)
                # Update user data after insert to db
                user = SynOrmUserQueries.get_user_by_username(user.username)
    
    
    def __update_product(name, username, new_price_key, new_max_key):
        SynOrmProductQueries.update_product(
                                name=name,
                                username=username,
                                price_100g=st.session_state[new_price_key],
                                max_per_day=st.session_state[new_max_key],
        )
    
    
    def __delete_product(name, username):
        SynOrmProductQueries.delete_product(name, username)
    
    
    user = SynOrmUserQueries.get_user_by_username(user.username)
    st.subheader("Продукты")
    products = sorted(user.products, key=lambda x: x.name)
    for i in range(len(products)):
        with st.container(border=True):
            col_upd_form, col_del = st.columns([10, 1])
            with col_upd_form:
                with st.form(key=f"{PRODUCTS_KEY_BASE}_product_{i}_form"):
                    col_name, col_price, col_max, col_upd_btn = st.columns(4)
                    with col_name:
                        st.markdown(f"**{products[i].name}**")
                    with col_price:
                        st.number_input(
                            label="Цена 100 гр (руб)", 
                            value=products[i].price_100g,
                            min_value=0.0,
                            step=0.01,
                            key=f"{PRODUCTS_KEY_BASE}_product_{i}_price",
                        )
                    with col_max:
                        st.number_input(
                            label="Макс. в день (гр)",
                            min_value=20.0,
                            value=products[i].max_per_day,
                            step=10.0,
                            key=f"{PRODUCTS_KEY_BASE}_product_{i}_max",
                        )
                    with col_upd_btn:
                        st.form_submit_button(
                            label="Подтвердить изменение",
                            type="primary",
                            on_click=__update_product,
                            kwargs={
                                "name": products[i].name,
                                "username": user.username,
                                "new_price_key": 
                                    f"{PRODUCTS_KEY_BASE}_product_{i}_price",
                                "new_max_key": 
                                    f"{PRODUCTS_KEY_BASE}_product_{i}_max",
                            },
                            use_container_width=True,
                        )
            with col_del:
                st.button(
                    label="✖️",
                    key=f"{PRODUCTS_KEY_BASE}_product_{i}_delete",
                    on_click=__delete_product,
                    kwargs={
                        "name": products[i].name,
                        "username": user.username,
                    },
                    use_container_width=True,
                    type="primary",
                )
            
            col_pfc, col_ready_to_eat, col_description = st.columns([2, 1, 2])
            with col_pfc:
                p = products[i].proteins_100g
                f = products[i].fats_100g
                c = products[i].carbs_100g
                st.markdown(
                    body=f"""
                    **Пищевая ценность** на **100 гр**:  
                    **Б**: {p:.2f} гр, **Ж**: {f:.2f} гр, **У**: {c:.2f} гр,  
                    **Калорийность**: {(p * 4.1 + f * 9.3 + c * 4.1):.2f} ккал
                    """
                )
            with col_ready_to_eat:
                st.markdown(
                    f"""
                    **Готов к употреблению**:  
                    {"Да" if products[i].ready_to_eat else "Нет"}
                    """
                )
            with col_description:
                description = products[i].description 
                if description is None or description == "":
                    description = "Отсутствует"
                st.markdown(
                    f"""**Описание**:  
                    {description}
                    """
                )
                